<template>
  <div class="avue-sidebar">
    <logo></logo>
    <top-search v-if="!keyCollapse" @openDvpDialog="openDvpDialog"></top-search>
    <el-scrollbar style="height: 93%">
      <div v-if="validatenull(menu)" class="avue-sidebar--tip">{{ $t('menuTip') }}</div>
      <el-menu unique-opened :default-active="nowTagValue" :default-openeds="openeds" mode="vertical" :show-timeout="200" :collapse="keyCollapse">
        <sidebar-item ref="sideBarItem" :menu="menu" :screen="screen" first :props="website.menu.props" :collapse="keyCollapse" @getOpeneds="getOpeneds"></sidebar-item>
      </el-menu>
    </el-scrollbar>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import logo from '../logo';
import sidebarItem from './sidebarItem';
import topSearch from '../top/top-search';

export default {
  name: 'sidebar',
  components: { sidebarItem, logo, topSearch },
  inject: ['index'],
  data() {
    return {
      openeds: [],
      isFor: true,
      forList: [],
      lastIndex: ''
    };
  },
  created() {
    this.index.openMenu();
  },
  computed: {
    ...mapGetters(['website', 'menu', 'tag', 'keyCollapse', 'screen', 'menuId']),
    nowTagValue: function () {
      return this.$router.$avueRouter.getValue(this.$route);
    }
  },
  methods: {
    /**
     * 获取需要展开的菜单
     */
    async getOpeneds(val) {
      this.openeds = [];
      this.isFor = true;
      for (let i = 0; i < this.menu.length; i++) {
        if (this.isFor) {
          this.lastIndex = i;
          await this.getChildren(this.menu[i], val, []);
        }
      }
    },

    /**
     * 对象中有子菜单时继续循环
     */
    async getChildren(item, val, pathStack) {
      // 更新当前路径栈
      const newPathStack = [...pathStack, item.path];

      if (item.path === val) {
        // 记录当前路径栈中的所有上级菜单
        this.openeds.push(...newPathStack);
        this.isFor = false;
        return;
      }

      if (item.children && item.children.length > 0) {
        for (let j = 0; j < item.children.length; j++) {
          const childrenItem = item.children[j];
          if (this.isFor) {
            await this.getChildren(childrenItem, val, newPathStack); // 确保递归调用完成
          }
          if (!this.isFor) {
            // 如果找到了目标菜单，则记录上级路径
            this.openeds.push(...newPathStack);
            break;
          }
        }
      }
    },
    openDvpDialog(item) {
      this.$refs.sideBarItem && this.$refs.sideBarItem.openDvpDrawer(item);
    }
  }
};
</script>
<style lang="scss" scoped></style>
